﻿namespace XC.Keys
{
    internal class XcRegistry
    {

        private Microsoft.Win32.RegistryKey rkey = Microsoft.Win32.Registry.CurrentUser;
        /// <summary>
        /// 写数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void SetValue(string name, string value)
        {
            if (IsExistRegeditName())//若存在
            {
                Microsoft.Win32.RegistryKey registryKey = rkey.OpenSubKey("SOFTWARE\\XCLINK", true);
                registryKey.SetValue(name, value);//写入数据
            }
            else//若不存在
            {
                Microsoft.Win32.RegistryKey software = rkey.CreateSubKey("SOFTWARE\\XCLINK");//创建注册表名称
                Microsoft.Win32.RegistryKey registryKey = rkey.OpenSubKey("SOFTWARE\\XCLINK", true);
                registryKey.SetValue(name, value);//写入数据
            }
            rkey.Close();
        }
        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetValue(string name)
        {
            if (IsExistRegeditName())
            {
                Microsoft.Win32.RegistryKey registryKey = rkey.OpenSubKey("SOFTWARE\\XCLINK", true);
                var info = registryKey.GetValue(name);
                if (info==null)
                {
                    return null;
                }
                return info.ToString();
            }
            else
            {
                return null; //未加载数据，需要加载密钥
            }
        }
        /// <summary>
        /// 判断注册表名称是否存在
        /// </summary>
        /// <returns></returns>
        public bool IsExistRegeditName()
        {
            var sotfware = rkey.OpenSubKey("SOFTWARE");
            var namelist = sotfware.GetSubKeyNames();
            foreach (var item in namelist)
            {
                if (item == "XCLINK")
                {
                    sotfware.Close();
                    return true;
                }
            }
            sotfware.Close();
            return false;
        }

        public void DeleteReg()
        {
            if (IsExistRegeditName())
            {
                rkey.DeleteSubKey("SOFTWARE\\XCLINK");//删除注册表名称
            }
        }
    }

}
